import path from 'path'
import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import { createHtmlPlugin } from 'vite-plugin-html'
import viteCompression from 'vite-plugin-compression'
// import viteImagemin from 'vite-plugin-imagemin'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'

const pathSrc = path.resolve(__dirname, 'src')
// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env: Record<string, any> = loadEnv(mode, process.cwd(), '')
  return {
    base: './',
    assetsInclude: ['**/*.gltf', '**/*.bin'],
    plugins: [
      react(),
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_NAME,
            injectScript: `<link rel="icon" type="image/svg+xml" href="${env.VITE_APP_ICON}"/>`
          }
        }
      }),
      viteCompression({
        algorithm: 'brotliCompress', // 也可以使用 gzip
        ext: '.br'
      }),
      ViteImageOptimizer({
        // 配置 JPEG 压缩
        jpeg: {
          quality: 20, // 设置JPEG图片质量
          progressive: true // 启用渐进式JPEG
        },
        jpg: {
          quality: 20, // 设置JPEG图片质量
          progressive: true // 启用渐进式JPEG
        },
        // 配置 PNG 压缩
        png: {
          quality: 50
        },
        // 支持多种图片格式优化
        webp: {
          quality: 50 // 设置webp图片质量
        }
      })
    ],
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return 'vendor' // 第三方库打包到 vendor
            }
            if (id.includes('src/views')) {
              const match = id.match(/src\/views\/([^/]+)/)
              if (match) {
                return `page-${match[1]}` // 按页面拆分
              }
            }
          },
          // 分离 CSS 文件到单独的目录
          assetFileNames: (assetInfo) => {
            if (assetInfo?.name?.endsWith('.css')) {
              return 'css/[name]-[hash][extname]' // CSS 文件放到 css/ 目录
            }
            // 其他静态资源（如图片、字体等）放到 assets/ 目录
            return 'assets/[name]-[hash][extname]'
          },
          // 分离 JS 文件到单独的目录
          entryFileNames: 'js/[name]-[hash].js', // JS 文件放到 js/ 目录
          chunkFileNames: 'js/[name]-[hash].js' // 动态导入的 JS 文件也放到 js/ 目录
        }
      }
    },
    resolve: {
      alias: {
        '@': pathSrc
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          additionalData: `@use "@/App.scss" as *;`
        }
      }
    },
    server: {
      host: '0.0.0.0',
      port: env.VITE_APP_PORT,
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          rewrite: (path) => path.replace(/^\/api/, ''),
          changeOrigin: true
        }
      }
    }
  }
})
